package org.hj.modules.act.rutask;

import com.alibaba.fastjson.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.hj.common.system.api.ISysBaseAPI;
import org.hj.common.system.vo.LoginUser;
import org.hj.common.util.SpringContextUtils;
import org.hj.modules.AcBusinessController;
import org.hj.modules.act.procdef.service.HiprocdefService;
import org.hj.modules.act.procdef.service.RuprocdefService;
import org.hj.modules.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.net.URLDecoder;
import java.util.*;

/**
 * 说明：待办任务
 */
@Controller
@RequestMapping(value="/rutask")
public class RuTaskController extends AcBusinessController {

	@Autowired
	private RuprocdefService ruprocdefService;

	
	@Autowired
	private HiprocdefService hiprocdefService;

	@Autowired
	private ISysBaseAPI baseAPI;
	
	/**待办任务列表
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/list")
	@ResponseBody
	public Object list(HttpServletRequest request) throws Exception{

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		String KEYWORDS = request.getParameter("KEYWORDS");						//关键词检索条件
		String STRARTTIME = request.getParameter("STRARTTIME");					//开始时间
		String ENDTIME = request.getParameter("ENDTIME");						//结束时间
		String USERNAME=sysUser.getUsername();//查询当前用户的任务(用户名查询)

		// TODO: 2020/6/15 查询任务时，所属角色要处理的任务
		List list= baseAPI.getRolesByUserId(sysUser.getId());//查询当前用户的任务(角色编码查询)
		String  RNUMBERS = Arrays.toString(list.toArray());
		RNUMBERS=RNUMBERS.replace("[","(");
		RNUMBERS=RNUMBERS.replace("]",")");


		List<PageData>	varList = ruprocdefService.list(KEYWORDS,STRARTTIME,ENDTIME,USERNAME,"");	//列出Rutask列表
		for(int i=0;i<varList.size();i++){
			varList.get(i).put("INITATOR", getInitiator(varList.get(i).getString("PROC_INST_ID_")));//流程申请人
		}
		map.put("varList", varList);
		map.put("result", errInfo);				//返回结果
		return map;
	}

	/**待办任务列表(只显示5条,用于后台顶部小铃铛左边显示)
	 * @param page
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping(value="/getList")
//	@ResponseBody
//	public Object getList(Page page) throws Exception{
//		PageData pd = new PageData();
//		Map<String,Object> map = new HashMap<String,Object>();
//		pd.put("USERNAME", Jurisdiction.getUsername()); 		//查询当前用户的任务(用户名查询)
//		pd.put("RNUMBERS", Jurisdiction.getRnumbers()); 		//查询当前用户的任务(角色编码查询)
//		page.setPd(pd);
//		page.setShowCount(5);
//		List<PageData>	varList = ruprocdefService.list(page);	//列出Rutask列表
//		List<PageData> pdList = new ArrayList<PageData>();
//		for(int i=0;i<varList.size();i++){
//			PageData tpd = new PageData();
//			tpd.put("NAME_", varList.get(i).getString("NAME_"));	//任务名称
//			tpd.put("PNAME_", varList.get(i).getString("PNAME_"));	//流程名称
//			pdList.add(tpd);
//		}
//		map.put("list", pdList);
//		map.put("taskCount", page.getTotalResult());
//		return map;
//	}
	
	/**待办任务数量
	 * @param page
	 * @return
	 * @throws Exception
	 */
//	@RequestMapping(value="/getTaskCount")
//	@ResponseBody
//	public Object getTaskCount(Page page) throws Exception{
//		Map<String,Object> map = new HashMap<String,Object>();
//		String errInfo = "success";
//		PageData pd = new PageData();
//		pd.put("USERNAME", Jurisdiction.getUsername()); 		//查询当前用户的任务(用户名查询)
//		pd.put("RNUMBERS", Jurisdiction.getRnumbers()); 		//查询当前用户的任务(角色编码查询)
//		page.setPd(pd);
//		page.setShowCount(5);
//		ruprocdefService.list(page);
//		map.put("taskCount", page.getTotalResult());
//		map.put("result", errInfo);
//		return map;
//	}
	
	/**去办理任务页面获取数据
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/getHandleData")
	@ResponseBody
	public Object getHandleData(@RequestBody JSONObject jsonObject,HttpServletRequest request)throws Exception{
		Map<String,Object> map = new HashMap<String,Object>();
		String errInfo = "success";
		String PROC_INST_ID_=jsonObject.getString("PROC_INST_ID_");
		String ID_=jsonObject.getString("ID_");

		List<Map>	varList = ruprocdefService.varList(PROC_INST_ID_);			//列出流程变量列表
		//去除一些不必要的数据
		List<Map> mapList=new ArrayList<>();
		for(Map map1:varList){
			if(!"id".equals(map1.get("NAME_").toString())&&!"RESULT".equals(map1.get("NAME_").toString())&&!"username".equals(map1.get("NAME_").toString())){
				mapList.add(map1);
			}
		}
		List<Map>	hitaskList = ruprocdefService.hiTaskList(PROC_INST_ID_);	//历史任务节点列表
		for(int i=0;i<hitaskList.size();i++){							//根据耗时的毫秒数计算天时分秒
			if(null != hitaskList.get(i).get("DURATION_")){
				Long ztime = Long.parseLong(hitaskList.get(i).get("DURATION_").toString());
				Long tian = ztime / (1000*60*60*24);
				Long shi = (ztime % (1000*60*60*24))/(1000*60*60);
				Long fen = (ztime % (1000*60*60*24))%(1000*60*60)/(1000*60);
				Long miao = (ztime % (1000*60*60*24))%(1000*60*60)%(1000*60)/1000;
				hitaskList.get(i).put("ZTIME", tian+"天"+shi+"时"+fen+"分"+miao+"秒");
			}
		}
		String FILENAME = URLDecoder.decode(jsonObject.getString("FILENAME"), "UTF-8");
		createXmlAndPngAtNowTask(PROC_INST_ID_,FILENAME);//生成当前任务节点的流程图片
		String imgSrcPath = PathUtil.getProjectpath()+ Const.FILEACTIVITI+FILENAME;
		map.put("imgSrc", "data:image/jpeg;base64,"+ ImageAnd64Binary.getImageStr(imgSrcPath)); //解决图片src中文乱码，把图片转成base64格式显示(这样就不用修改tomcat的配置了)
		map.put("varList", mapList);
		map.put("list", varList);
		map.put("hitaskList", hitaskList);
		map.put("result", errInfo);				//返回结果
		return map;
	}
	
	/**办理任务
	 * @param
	 * @throws Exception
	 */
	@RequestMapping(value="/handle")
	@ResponseBody
	public Object handle(@RequestBody JSONObject jsonObject,HttpServletRequest request) throws Exception{

		LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        String PROC_INST_ID_=jsonObject.getString("PROC_INST_ID_");
        List<Map>	varList = ruprocdefService.varList(PROC_INST_ID_);			//列出流程变量列表
        List<Map>	hitaskList = ruprocdefService.hiTaskList(PROC_INST_ID_);	//历史任务节点列表

      //查询当前流程节点
        Map map1 = hitaskList.get(0);
        String taskDefKey = map1.get("ACT_ID_").toString();

		String id =null;
		String type =null;
		for (Map map:varList) {
			if("id".equals(map.get("NAME_").toString())){
				 id = map.get("TEXT_").toString();
			}
			if("单证类型".equals(map.get("NAME_").toString())){
				type = map.get("TEXT_").toString();
			}
		}


		Map<String,Object> zmap = new HashMap<String,Object>();
		String errInfo = "success";
		HttpSession session = SpringContextUtils.getHttpServletRequest().getSession();
		//PageData pd = new PageData(request);
		String taskId = jsonObject.getString("ID_");	//任务ID
		String sfrom = "";
		Object ofrom = getVariablesByTaskIdAsMap(taskId,"审批结果");
		if(null != ofrom){
			sfrom = ofrom.toString();
		}
		Map<String,Object> map = new LinkedHashMap<String, Object>();
		String OPINION = sfrom + sysUser.getRealname() + ","+jsonObject.getString("OPINION");//审批人的姓名+审批意见
		String msg = jsonObject.getString("msg");
		if("yes".equals(msg)){								//批准
			map.put("审批结果", "【批准】" + OPINION);		//审批结果
			setVariablesByTaskIdAsMap(taskId,map);			//设置流程变量
			setVariablesByTaskId(taskId,"RESULT","批准");
			completeMyPersonalTask(taskId);

			if("flow100".equals(taskDefKey)){

                new RuTaskFact().update(type,id,"3");

            }


		}else{												//驳回
			map.put("审批结果", "【驳回】" + OPINION);		//审批结果
			setVariablesByTaskIdAsMap(taskId,map);			//设置流程变量
			setVariablesByTaskId(taskId,"RESULT","驳回");
			completeMyPersonalTask(taskId);

			new RuTaskFact().update(type,id,"5");
		}
//		try{
//			removeVariablesByPROC_INST_ID_(jsonObject.getString("PROC_INST_ID_"),"RESULT");			//移除流程变量(从正在运行中)
//		}catch(Exception e){
//			/*此流程变量在历史中**/
//		}
		try{
			String ASSIGNEE_ = jsonObject.getString("ASSIGNEE_");							//下一待办对象

			/*if(Tools.notEmpty(ASSIGNEE_)){
				setAssignee(session.getAttribute("TASKID").toString(),ASSIGNEE_);	//指定下一任务待办对象
			}else{
				Object os = session.getAttribute("YAssignee");
				if(null != os && !"".equals(os.toString())){
					ASSIGNEE_ = os.toString();										//没有指定就是默认流程的待办人
				}else{
					//trySendSms(zmap,pd); 			//没有任务监听时，默认流程结束，发送站内信给任务发起人
				}
			}*/

            Object os = session.getAttribute("YAssignee");
            if(null != os && !"".equals(os.toString())){
                ASSIGNEE_ = os.toString();										//没有指定就是默认流程的待办人
            }else{
                //trySendSms(zmap,pd); 			//没有任务监听时，默认流程结束，发送站内信给任务发起人
            }

			zmap.put("ASSIGNEE_",ASSIGNEE_);		//用于给待办人发送新任务消息
		}catch(Exception e){
			zmap.put("ASSIGNEE_","null");
			/*手动指定下一待办人，才会触发此异常。
			 * 任务结束不需要指定下一步办理人了,发送站内信通知任务发起人**/
			//trySendSms(zmap,pd);
		}
		if(Tools.notEmpty(jsonObject.getString("COPYTOER"))) {
			//String PROC_INST_ID_=request.getParameter("PROC_INST_ID_");
			//List<Map>	varList = ruprocdefService.varList(PROC_INST_ID_);			//列出流程变量列表
			this.sendSms(jsonObject.getString("COPYTOER"), jsonObject.getString("CREMARKS"), varList, map.get("审批结果").toString());			//发站内信给抄送对象
		}
		zmap.put("result", errInfo);				//返回结果
		return zmap;
	}
	
	/**发送站内信
	 * @param
	 * @param pd
	 * @throws Exception
	 */
	public void trySendSms(Map<String,Object> zmap,PageData pd)throws Exception{
		List<PageData>	hivarList = hiprocdefService.hivarList(pd);			//列出历史流程变量列表
		for(int i=0;i<hivarList.size();i++){
			if("USERNAME".equals(hivarList.get(i).getString("NAME_"))){
				sendSms(hivarList.get(i).getString("TEXT_"));
				zmap.put("HJSMS",hivarList.get(i).getString("TEXT_"));
				break;
			}
		}
	}

	/**发站内信通知审批结束
	 * @param USERNAME
	 * @throws Exception
	 */
	public void sendSms(String USERNAME) throws Exception{
		/*PageData pd = new PageData();
		pd.put("SANME_ID", this.get32UUID());			//ID
		pd.put("SEND_TIME", DateUtil.getTime());		//发送时间
		pd.put("FHSMS_ID", this.get32UUID());			//主键
		pd.put("TYPE", "1");							//类型1：收信
		pd.put("FROM_USERNAME", USERNAME);				//收信人
		pd.put("TO_USERNAME", "系统消息");
		pd.put("CONTENT", "您申请的任务已经审批完毕,请到已办任务列表查看");
		pd.put("STATUS", "2");
		fhsmsService.save(pd);*/
	}

	/**发站内信给抄送对象
	 * @param USERNAME
	 * @throws Exception
	 */
	public void sendSms(String USERNAME, String CREMARKS, List<Map> varList, String OPINION) throws Exception{
		/*PageData pd = new PageData();
		pd.put("SANME_ID", this.get32UUID());			//ID
		pd.put("SEND_TIME", DateUtil.getTime());		//发送时间
		pd.put("FHSMS_ID", this.get32UUID());			//主键
		pd.put("TYPE", "1");							//类型1：收信
		pd.put("FROM_USERNAME", USERNAME);				//收信人
		pd.put("TO_USERNAME", "任务抄送");
		StringBuffer sb = new StringBuffer();
		sb.append("[任务抄送]<br>\n");
		sb.append("-------------------------------------------------------------------------------------------------------------<br>\n");
		sb.append("任务由" + Jurisdiction.getName() + "(" + Jurisdiction.getUsername() + ")" + "抄送<br>\n");
		sb.append("备注说明："+CREMARKS + "<br>\n");
		sb.append("申请事项-------------------------------------------------------------------------------------------------<br>\n");
		for(int i=0;i < varList.size();i++) {
			sb.append(varList.get(i).get("NAME_") + "：" + varList.get(i).get("TEXT_") + "<br>\n");
		}
		sb.append("审批意见-------------------------------------------------------------------------------------------------<br>\n");
		sb.append(OPINION.replace(",fh,", ""));
		pd.put("CONTENT", sb.toString());
		pd.put("STATUS", "2");
		fhsmsService.save(pd);*/
	}



}
